#!/usr/bin/env python
# -*= coding: utf-8 -*-
# http://www.oreillynet.com/pub/h/476 Encode Text for URLs
# http://evanjones.ca/python-utf8.html How to Use UTF-8 with Python
# http://abitno.linpie.com/a-small-translate-tool.html 寫了一個小小的翻譯工具
import sys
import os
from urllib import urlencode
import urllib2
import json
from translate import *

class GoogleTranslate( Translate ):
	base_uri = "http://www.ajax.googleapis.com/ajax/services/language"

	def get_json( self, uri ):
		try:
			response = urllib2.urlopen( uri )
		except:
			response = { "responseData": { "language": "", "translatedText":""
				} }
		return json.load(response)

	def detect( self, text ):
		query=urlencode( { 'v': '1.0', 'q': text } )
		uri="%s/detect?%s" % ( self.base_uri, query )
		return self.get_json( uri )['responseData']['language']

	def translate( self, text, fr="en", to="zh-TW" ):
		"""If you want to know which languages are supported, please 
		   visit http://translate.google.com.
		   Because Google don't provide any API to get languages.
		"""
		query=urlencode( { 'v': '1.0', 'langpair': '%s|%s' % (fr,to),
				'q': text } )
		uri="%s/translate?%s" % (self.base_uri, query )
		return self.get_json( uri )['responseData']['translatedText']

if __name__ == "__main__":
	t = GoogleTranslate()
	print t.translate( "test" )
	print t.detect( "繁體中文" )

